/**
 *   当前widget对象
 */

import { ref, provide, inject, computed, nextTick, watch } from "vue";
import { designEditKey } from "./keys";
import strUtil from "@/utils/StrUtil";
import type { TypeWidget, TypeDesignProvide, TypeWidgetStyle } from "@/types/TypeDesign";

export function useWidget(widget: TypeWidget) {
  const { designWidgetList, setDesignSelectWidget, emitHistoryChange, designSelectedWidget } = inject(
    designEditKey
  ) as TypeDesignProvide;

  const deleteWidget = () => { };

  const copyWidget = () => { };

  // 复制组件--目前只针对于组件，如果是布局的话，涉及的ID都要刷新一遍
  const _copyWidget = () => {
    const newWidget = strUtil.deepClone(widget);
    if (newWidget.component.indexOf("zw-") !== -1) {
      newWidget.id = newWidget.component.substring(3, newWidget.component.length) + "_" + strUtil.generateId();
    } else {
      newWidget.id = newWidget.component + "_" + strUtil.generateId();
    }
    newWidget.attrs.id = newWidget.id;
    newWidget.attrWidgets.forEach((v) => {
      if (v.key === "id") {
        v.value = newWidget.id;
      }
    });

    if (newWidget.widgetList && newWidget.widgetList.length > 0) {
      processItemsId(newWidget.widgetList);
    }

    return newWidget;
  };

  const processItemsId = (items: any[]) => {
    //修改所有子项的ID
    items.forEach((v) => {
      if (v.component.indexOf("zw-") !== -1) {
        v.id = v.component.substring(3, v.component.length) + "_" + strUtil.generateId();
      } else {
        v.id = v.component + "_" + strUtil.generateId();
      }
      v.attrs.id = v.id;
      v.attrWidgets.forEach((vv) => {
        if (vv.key === "id") {
          vv.value = v.id;
        }
      });
      if (v.widgetList && v.widgetList.length > 0) {
        processItemsId(v.widgetList);
      }
    });
  };

  const mouseWidget = ref<TypeWidget>();
  /**
   *  鼠标移入：
   *  1. 设置当前的widget为鼠标移入的widget
   *  2. 修改当前widget的为虚线的边框
   */
  const mouseEnter = () => {
    mouseWidget.value = widget;
  };

  /**
   *  鼠标移出：
   *  1. 设置当前的widget为空
   *  2. 修改当前widget的类去除虚线边框
   */
  const mouseLeave = () => {
    mouseWidget.value = undefined;
  };

  const startX = ref(0);
  const startY = ref(0);
  const startWidth = ref(0);
  const startHeight = ref(0);
  const isResizing = ref(false);

  // 拖拽拉伸组件高度（Y轴方向拖拽）
  const handleDragYStartEvent = (e) => {
    // console.log("========>handleDragYStartEvent");

    startY.value = e.clientY || e.touches[0].clientY;
    isResizing.value = true;
    startHeight.value = widget.style.height;

    document.onmousemove = (event) => {
      // console.log("Y document.onmousemove", isResizing.value);
      if (!isResizing.value) {
        return;
      }
      const eventY = event.clientY || event.touches[0].clientY;
      const moveY = eventY - startY.value;
      widget.style.height = startHeight.value + moveY;
    };

    document.onmouseup = (event) => {
      // console.log("Y document.onmouseup", isResizing.value);
      if (!isResizing.value) {
        return false;
      }
      document.onmousemove = null;
      document.onmouseup = null;
      isResizing.value = false;
      const eventY = event.clientY || event.changedTouches[0].clientY;
      if (eventY === startY.value) {
        return false;
      }
    };
  };

  // 拖拽拉伸组件宽度(X轴方向拖拽)
  const handleDragXStartEvent = (e) => {
    // console.log("========>handleDragXStartEvent");

    startX.value = e.clientX || e.touches[0].clientX;
    isResizing.value = true;
    startWidth.value = widget.style.width;

    document.onmousemove = (event) => {
      // console.log("X document.onmousemove", isResizing.value);
      if (!isResizing.value) {
        return;
      }
      const eventX = event.clientX || event.touches[0].clientX;
      const moveX = eventX - startX.value;
      widget.style.width = startWidth.value + moveX;
    };

    document.onmouseup = (event) => {
      // console.log("X document.onmouseup", isResizing.value);
      if (!isResizing.value) {
        return false;
      }
      document.onmousemove = null;
      document.onmouseup = null;
      isResizing.value = false;
      const eventX = event.clientX || event.changedTouches[0].clientX;
      if (eventX === startX.value) {
        return false;
      }
    };
  };

  // 拖拽拉伸组件拉伸宽高(X、Y轴方向拖拽)
  const handleDragXYStartEvent = (e) => {
    // console.log("========>handleDragXYStartEvent");

    startX.value = e.clientX || e.touches[0].clientX;
    startY.value = e.clientY || e.touches[0].clientY;
    isResizing.value = true;
    startWidth.value = widget.style.width;
    startHeight.value = widget.style.height;

    document.onmousemove = (event) => {
      // console.log("XY document.onmousemove", isResizing.value);
      if (!isResizing.value) {
        return;
      }
      const eventX = event.clientX || event.touches[0].clientX;
      const eventY = event.clientY || event.touches[0].clientY;
      const moveX = eventX - startX.value;
      const moveY = eventY - startY.value;
      widget.style.width = startWidth.value + moveX;
      widget.style.height = startHeight.value + moveY;
      // console.log("X width", widget.width);
      // console.log("Y height", widget.height);
    };

    document.onmouseup = (event) => {
      // console.log("XY document.onmouseup", isResizing.value);
      if (!isResizing.value) {
        return false;
      }
      document.onmousemove = null;
      document.onmouseup = null;
      isResizing.value = false;
      const eventX = event.clientX || event.changedTouches[0].clientX;
      const eventY = event.clientY || event.changedTouches[0].clientY;
      if (eventX === startX.value || eventY === startY.value) {
        return false;
      }
    };
  };

  /**
   *  点击选择widget
   *  1. 设置当前选中的widget
   *  2. 修改当前选中的widget的边框为实线
   */
  const selectWidget = () => {
    setDesignSelectWidget(widget);
  };

  const getIsWidgetSelect = computed(() => {
    if (designSelectedWidget.value && widget.id === designSelectedWidget.value.id) {
      return true;
    }
    return false;
  });

  const getWidgetSelectClass = computed(() => {
    //组件的类
    let widgetSelectClass = "";

    // 组件自身的类
    if (widget.class && widget.class.length != 0) {
      const str = widget.class.toString();
      const tt = str.replace(/,/g, " ");
      widgetSelectClass = widgetSelectClass + tt;
    }

    // 如果选择了当前组件，则高亮显示
    if (getIsWidgetSelect.value) {
      widgetSelectClass = widgetSelectClass + " zw_selected";
    }

    // 如果鼠标经过了当前的widget, 并且当前的widget没有被选择，标记出当前经过的组件
    if (!strUtil.isEmpty(mouseWidget.value) && mouseWidget.value!.id === widget.id && !getIsWidgetSelect.value) {
      widgetSelectClass = widgetSelectClass + " zw_mouseEnter";
    }
    // console.log("cClass", widgetSelectClass.value);

    return widgetSelectClass;
  });

  const getWidgetStyle = computed(() => {
    const mstyle: TypeWidgetStyle = {
      width: widget.style.width + "px",
      height: widget.style.height + "px",
    };
    if (widget.style.borderWidth && widget.style.borderWidth! > 0) {
      //边框
      if (widget.style.borderPos!.toString() === "1,1,1,1") {
        mstyle.border = `${widget.style.borderStyle} ${widget.style.borderWidth}px ${widget.style.borderColor}`;
      } else {
        if (widget.style.borderPos![0] === 1) {
          mstyle.borderTop = `${widget.style.borderStyle} ${widget.style.borderWidth}px ${widget.style.borderColor}`;
        }
        if (widget.style.borderPos![1] === 1) {
          mstyle.borderRight = `${widget.style.borderStyle} ${widget.style.borderWidth}px ${widget.style.borderColor}`;
        }
        if (widget.style.borderPos![2] === 1) {
          mstyle.borderBottom = `${widget.style.borderStyle} ${widget.style.borderWidth}px ${widget.style.borderColor}`;
        }
        if (widget.style.borderPos![3] === 1) {
          mstyle.borderLeft = `${widget.style.borderStyle} ${widget.style.borderWidth}px ${widget.style.borderColor}`;
        }
      }
    }
    if (Number(widget.style.borderRadius) > 0) {
      //圆角
      if (widget.style.borderRadiusPos!.toString() === "1,1,1,1") {
        mstyle.borderRadius = `${widget.style.borderRadius}px`;
      } else {
        if (widget.style.borderRadiusPos![0] === 1) {
          mstyle.borderTopLeftRadius = `${widget.style.borderRadius}px`;
        }
        if (widget.style.borderRadiusPos![1] === 1) {
          mstyle.borderTopRightRadius = `${widget.style.borderRadius}px`;
        }
        if (widget.style.borderRadiusPos![2] === 1) {
          mstyle.borderBottomRightRadius = `${widget.style.borderRadius}px`;
        }
        if (widget.style.borderRadiusPos![3] === 1) {
          mstyle.borderBottomLeftRadius = `${widget.style.borderRadius}px`;
        }
      }
    }

    if (widget.style.isBorderShadow!) {
      mstyle.boxShadow = `${widget.style.borderShadow![0]}px ${widget.style.borderShadow![1]}px ${widget.style.borderShadow![2]
        }px ${widget.style.borderShadow![3]}px ${widget.style.borderShadow![4]}`;
    }

    if (widget.style.isBorderShadowInset!) {
      const ss = `${widget.style.borderShadowInset![0]}px ${widget.style.borderShadowInset![1]}px ${widget.style.borderShadowInset![2]
        }px ${widget.style.borderShadowInset![3]}px ${widget.style.borderShadowInset![4]} inset`;
      if (mstyle.boxShadow) {
        mstyle.boxShadow = mstyle.boxShadow + "," + ss;
      } else {
        mstyle.boxShadow = ss;
      }
    }

    if (widget.style.backgroundColorType! !== "") {
      if (widget.style.backgroundColorType! === "color") {
        mstyle.background = widget.style.backgroundColorValue;
      } else if (widget.style.backgroundColorType! === "linear") {
        mstyle.background = `linear-gradient(to ${widget.style.backgroundColorLinear![0]}, ${widget.style.backgroundColorLinear![1]
          }, ${widget.style.backgroundColorLinear![2]})`;
      } else if (widget.style.backgroundColorType! === "image") {
        // mstyle.background = widget.style.backgroundColorValue;
      }
    }

    if (widget.style.padding! !== undefined) {
      if (widget.style.padding[0] != 0) {
        mstyle.paddingTop = widget.style.padding[0] + "px";
      }
      if (widget.style.padding[1] != 0) {
        mstyle.padingRight = widget.style.padding[1] + "px";
      }
      if (widget.style.padding[2] != 0) {
        mstyle.paddingBottom = widget.style.padding[2] + "px";
      }
      if (widget.style.padding[3] != 0) {
        mstyle.paddingLeft = widget.style.padding[3] + "px";
      }
    }

    // 文字
    if (widget.style.text!) {
      mstyle.color = widget.style.text.color;
      mstyle.fontSize = widget.style.text.fontSize + "px";
      if (widget.style.text.fontWeight == "bold") {
        mstyle.fontWeight = "bold";
      } else if (widget.style.text.fontWeight == "medium") {
        mstyle.fontWeight = 500;
      }
      mstyle.letterSpacing = widget.style.text.letterSpacing + "px";
      mstyle.lineHeight = widget.style.text.lineHeight + "px";
      if (widget.style.text.lines !== 0) {
        mstyle.overflow = "hidden";
        mstyle.textOverflow = "ellipsis";
        mstyle.display = "-webkit-box";
        mstyle.webkitBoxOrient = "vertical";
        mstyle.webkitLineClamp = widget.style.text.lines;
      }
      if (widget.style.text.textAlign !== "left") {
        mstyle.textAlign = widget.style.text.textAlign;
      }
      if (widget.style.text.textStyle == "italic") {
        mstyle.fontStyle = "italic";
      } else {
        mstyle.fontStyle = "";
        mstyle.textDecoration = widget.style.text.textStyle;
      }

      if (widget.style.text.isBorderShadow) {
        mstyle.textShadow = `${widget.style.text.borderShadow![0]}px ${widget.style.text.borderShadow![1]}px ${widget.style.text.borderShadow![2]}px ${widget.style.text.borderShadow![3]}`
      }

    }

    return mstyle;
  });

  return {
    selectWidget,

    copyWidget,
    deleteWidget,

    mouseEnter,
    mouseLeave,

    handleDragXYStartEvent,
    handleDragXStartEvent,
    handleDragYStartEvent,

    getIsWidgetSelect,
    getWidgetSelectClass,
    isResizing,
    getWidgetStyle,
  };
}
